package com.sheng.leetcode.year2022.swordfingeroffer.day07;

import org.junit.Test;

/**
 * @author liusheng
 * @date 2022/09/06
 *
 * 剑指 Offer 27. 二叉树的镜像
 *
 * 请完成一个函数，输入一个二叉树，该函数输出它的镜像。
 *
 * 例如输入：
 *      4
 *    /   \
 *   2     7
 *  / \   / \
 * 1   3 6   9
 * 镜像输出：
 *      4
 *    /   \
 *   7     2
 *  / \   / \
 * 9   6 3   1
 *
 * 示例 1：
 *
 * 输入：root = [4,2,7,1,3,6,9]
 * 输出：[4,7,2,9,6,3,1]
 *
 * 限制：
 *
 * 0 <= 节点个数 <= 1000
 *
 * 注意：本题与主站 226 题相同：https://leetcode-cn.com/problems/invert-binary-tree/
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/er-cha-shu-de-jing-xiang-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Sword0027 {

    @Test
    public void test01() {
        TreeNode root = new TreeNode(4);
        TreeNode left = new TreeNode(2);
        left.left = new TreeNode(1);
        left.right = new TreeNode(3);
        TreeNode right = new TreeNode(7);
        right.left = new TreeNode(6);
        right.right = new TreeNode(9);
        root.left = left;
        root.right = right;
        System.out.println(new Solution27().mirrorTree(root));
    }
}
class Solution27 {

    TreeNode t;
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        t = new TreeNode(root.val);
        image(t, root);
        return t;
    }

    public void image(TreeNode t1, TreeNode t2) {
        // 如果第二个结点的右结点不为空，则将t2右结点的值赋给t1的左结点，并迭代
        if (t2.right != null) {
            t1.left = new TreeNode(t2.right.val);
            image(t1.left, t2.right);
        }
        if (t2.left != null) {
            t1.right = new TreeNode(t2.left.val);
            image(t1.right, t2.left);
        }
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
